package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @description:
 * @author: LiuXingYu
 * @date: 2021/9/23 15:49
 */

@Component
public class OrderTccActionImpl implements OrderTccAction {

    @Autowired
    private OrderMapper orderMapper;

    @Transactional // 控制本地事务
    @Override
    public boolean prepare(BusinessActionContext businessActionContext, Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        orderMapper.insertFrozen(
                new Order(orderId, userId, productId, count, money, 0));
        // 保存一阶段的成功标记
        ResultHolder.setResult(OrderTccAction.class, businessActionContext.getXid(), "p");
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean commit(BusinessActionContext businessActionContext) {
        // 二阶段检查标记是否存在, 不存在则不再执行二阶段代码
        //      1.二阶段已经执行过;
        //      2.一阶段失败;
        if (ResultHolder.getResult(OrderTccAction.class, businessActionContext.getXid()) == null) {
            return true;
        }

        Long orderId = Long.valueOf(businessActionContext.getActionContext("orderId").toString());
        orderMapper.updateStatus(orderId, 1);
        // 二阶段执行完成, 删除标记
        ResultHolder.removeResult(OrderTccAction.class, businessActionContext.getXid());
        return true;
    }

    @Transactional
    @Override
    public synchronized boolean rollback(BusinessActionContext businessActionContext) {
        if (ResultHolder.getResult(OrderTccAction.class, businessActionContext.getXid()) == null) {
            return true;
        }
        long orderId = Long.parseLong(businessActionContext.getActionContext("orderId").toString());
        orderMapper.deleteById(orderId);
        ResultHolder.removeResult(OrderTccAction.class, businessActionContext.getXid());
        return true;
    }
}
